<template>
    <div v-loading="commit" element-loading-text="数据正在提交" class="console-page">
        <el-row class="forbid-select" style="padding: 5px;height: 100%;">
            <!-- 页面左侧，显示所有标题 -->
            <el-col class="title-page">
                <el-scrollbar style="width: 100%;height: 100%">
                    <div v-if="newItem">
                        <ul>
                            <li class="el-dropdown-menu__item is-disabled ">new</li>
                        </ul>
                    </div>
                    <div v-else>
                        <ul>
                            <li :class="`el-dropdown-menu__item ${currentTitle === item ? 'title-select' : ''} font-auto-resize title-item`"
                                @click="clickTitle(item)" v-for="(item, index) in title" :key="index" ref="titleRef">
                                {{ item }}
                            </li>
                        </ul>
                    </div>
                </el-scrollbar>
                <el-button :icon="getIcon('plus')" circle class="button-auto-resize" @click="addNewItem"
                    style="position: absolute;bottom:5px;left: 5px" />
                <el-button :icon="getIcon('link')" circle class="button-auto-resize" @click="cache"
                    style="position: absolute;bottom: 5px;right: 5px" />
            </el-col>
            <el-col class="content-page">
                <el-scrollbar style="height: calc(100% - 10px);width: 100%;margin: 5px 0" ref="scrollbarRef">
                    <div v-if="newItem">
                        <el-col :span="12" style="padding:0 3px;">
                            <el-card :body-style="{ padding: '0px' }" shadow="hover"
                                style="margin-bottom:5px;min-width: 220px;" ref="dcRef" class="forbid-select">
                                <el-row>
                                    <el-col :span="1">
                                        <div class="newButton" @click.prevent="modifySetting(newDict, true)"
                                            style="z-index: 999;" />
                                    </el-col>
                                    <el-col :span="23" style="padding: 10px;">
                                        <el-form :model="newDict" ref="newDictRef" spellcheck="false"
                                            :hide-required-asterisk="true" :rules="rules" @submit.native.prevent>
                                            <el-form-item label="字典类别" prop="classCode">
                                                <el-select class="input-auto-resize" style="width: 100%;"
                                                    v-model="newDict.classCode" filterable allow-create
                                                    default-first-option placeholder="请选择类别">
                                                    <el-option v-for="item in title" :key="item" :label="item"
                                                        :value="item">
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                            <el-form-item label="字典名称" prop="name">
                                                <el-input class="input-auto-resize" v-model="newDict.name" />
                                            </el-form-item>
                                            <el-form-item label="字典类型" prop="valueType">
                                                <el-row>
                                                    <el-radio-group v-model="newDict.valueType"
                                                        class="input-auto-resize">
                                                        <el-radio-button :value="1">String</el-radio-button>
                                                        <el-radio-button :value="0">Boolean</el-radio-button>
                                                    </el-radio-group>
                                                </el-row>
                                            </el-form-item>
                                            <el-form-item label="字典内容" prop="value">
                                                <el-input class="input-auto-resize" v-model="newDict.inputValue"
                                                    v-if="newDict.valueType === 1" />
                                                <el-row v-else>
                                                    <el-radio-group v-model="newDict.selectValue"
                                                        class="input-auto-resize">
                                                        <el-radio-button value="1">true</el-radio-button>
                                                        <el-radio-button value="0">false</el-radio-button>
                                                    </el-radio-group>
                                                </el-row>
                                            </el-form-item>
                                            <el-form-item label="备注描述" prop="remark">
                                                <el-input class="input-auto-resize" v-model="newDict.remark" />
                                            </el-form-item>
                                        </el-form>
                                    </el-col>
                                </el-row>
                            </el-card>
                        </el-col>
                    </div>
                    <div v-else-if="dicts.length === 0">
                        <div class="empty-data">
                            暂无数据
                        </div>
                    </div>
                    <div v-else>
                        <VueDraggable v-model="dicts" chosenClass="chosenClass" ghostClass="ghostClass"
                            :forceFallback="true" dragClass="dragClass" @start="start" @end="end" :disabled="true"
                            ref="draggableRef" :animation="150">
                            <div v-waterfall>
                                <el-card shadow="hover" ref="dcRef" class="forbid-select dict-card" :key="index"
                                    v-for="(element, index) in dicts">
                                    <div class="placeholder card-modal" v-if="isDragging" />
                                    <el-row>
                                        <el-col :span="1">
                                            <div class="saveButton cursor-pointer"
                                                @click.prevent="modifySetting(element)" style="z-index: 999;" />
                                        </el-col>
                                        <el-col :span="23" style="padding:10px">
                                            <el-form :model="element" ref="dictRef" spellcheck="false"
                                                :hide-required-asterisk="true" @submit.native.prevent>
                                                <el-form-item label="字典名称" prop="name">
                                                    <el-input class="input-auto-resize" v-model="element.name"
                                                        disabled />
                                                </el-form-item>
                                                <el-form-item label="字典类型" prop="classCode">
                                                    <el-row>
                                                        <el-radio-group v-model="element.valueType"
                                                            class="input-auto-resize" disabled>
                                                            <el-radio-button :value="1">String</el-radio-button>
                                                            <el-radio-button :value="0">Boolean</el-radio-button>
                                                        </el-radio-group>
                                                    </el-row>
                                                </el-form-item>
                                                <el-form-item label="字典内容" prop="value">
                                                    <el-input class="input-auto-resize" v-model="element.value"
                                                        v-if="element.valueType === 1" />
                                                    <el-row v-else>
                                                        <el-radio-group v-model="element.value"
                                                            class="input-auto-resize">
                                                            <el-radio-button value="1">true</el-radio-button>
                                                            <el-radio-button value="0">false</el-radio-button>
                                                        </el-radio-group>
                                                    </el-row>
                                                </el-form-item>
                                                <el-form-item label="备注描述" prop="value">
                                                    <el-input class="input-auto-resize" v-model="element.remark" />
                                                </el-form-item>
                                            </el-form>
                                        </el-col>
                                    </el-row>
                                </el-card>
                            </div>
                        </VueDraggable>
                    </div>
                </el-scrollbar>
            </el-col>
        </el-row>
    </div>

</template>

<script setup>
import { useElMessage, useEventListener, useRequest } from "@usehook"
import { getElementSize, getIcon } from "@/utils/tools"
import { VueDraggable } from 'vue-draggable-plus'

let title = $ref([])
let dicts = ref([])
let currentTitle = $ref("")
let newItem = $ref(false)
let newDict = $ref({ classCode: "", name: "", valueType: 1, inputValue: "", selectValue: "1", remark: "", sequence: "" })
let rules = $ref({
    classCode: [
        { required: true, message: '字典类别不能为空', trigger: 'change' }
    ],
    name: [
        { required: true, message: '字典名称不能为空', trigger: 'change' }
    ]
})

let isDragging = $ref(false)
let commit = $ref(false)
let dictBak = $ref({})

const commitSort = () => {
    commit = true
    try {
        useRequest({ url: "/system/updateSort", data: dicts.value, classCode: currentTitle, method: "post" }).then(resp => {
            if (resp && resp.status) {
                useElMessage(resp.message)
            } else {
                useRequest({ url: '/system/content', title: currentTitle }).then(resp => {
                    if (resp && resp.status) {
                        dicts.value = resp.data
                    }
                });
            }
        })
    } catch (e) {

    } finally {
        commit = false
    }
}

const start = (el) => {
    const offsetWidth = getElementSize(document.querySelector(".title-page"), "width")
    let left = el.originalEvent.x - 19 - offsetWidth
    let top = el.originalEvent.y - 98

    nextTick(() => {
        const chosenClass = document.querySelectorAll('.chosenClass')[1]
        //调整被拖起的页签的位置  transform: translate3d(0, 0, 0);
        chosenClass.style.left = 0
        chosenClass.style.top = 0
        chosenClass.style.borderRadius = "5px"
        chosenClass.style.background = "rgba(255,255,255,.5)"
        chosenClass.style.backdropFilter = "var(--overlay-background-filter-blur)"
        chosenClass.style.transform = `translate3d(${left}px, ${top}px, 0)`
    })
}

const end = () => {
    for (let index in dicts.value) {
        dicts.value[index].rn = parseInt(index) + 1
        console.log(dicts.value[index].rn, dicts.value[index].name, dicts.value[index].value)
    }
}

const cache = () => {
    useRequest({ url: "/system/cache", method: "post" }).then(resp => {
        if (resp && resp.status) {
            useElMessage(resp.message)
        }
    })
}

const addNewItem = () => {
    newItem = !newItem
}

const clickTitle = (item) => {
    currentTitle = item
    useRequest({ url: '/system/content', title: item }).then((resData) => {
        if (resData && resData.status) {
            dicts.value = resData.data
        }
    })
}

const newDictRef = $ref(null)

const modifySetting = (data, newItem) => {
    if (isDragging) return
    if (newItem) {
        newDictRef.validate((valid) => {
            if (valid) {
                setData(data, true);
            } else {
                return false;
            }
        });
    } else {
        setData(data, false)
    }
}

const setData = (data, newItem) => {
    useRequest({ ...data, url: "/system/modify", method: "post" }).then((resData) => {
        if (resData.status) {
            getSetting()
            if (resData.message) useElMessage(resData.message);
            if (newItem) {
                addNewItem()
                newDict = {
                    classCode: "",
                    name: "",
                    valueType: 1,
                    inputValue: "",
                    selectValue: "1",
                    remark: "",
                    sequence: ""
                }
            }
        } else {
            if (resData.message) useElMessage.error(resData.message);
        }
    });

}

const getSetting = () => { //获取所有标题及对应的明细信息
    useRequest({ url: '/system/title' }).then((resData) => {
        if (resData) {
            if (resData.status) {
                title = resData.data.sort()
            } else {
                if (resData.message) useElMessage.error(resData.message);
            }
        }
        if (currentTitle) {
            useRequest({ url: '/system/content', title: currentTitle }).then((resData) => {
                if (resData && resData.status) {
                    dicts.value = resData.data
                }
            })
        }
    })
}

const draggableRef = ref("draggableRef")

const drag = (e) => {
    if (e.key === 'F1' && !commit && !isDragging && dicts.value.length) {
        isDragging = true
        console.log(draggableRef.value?.resume)

        draggableRef.value?.resume()
        dictBak = dicts.value.reduce((acc, curr, index) => {
            acc[index] = curr
            return acc
        }, {})
        if (document.querySelector('.dragClass')) document.querySelector('.dragClass').style.opacity = 1
    }
}

const dragEnd = (e) => {
    if (e.key === "F1" && dicts.value.length) {
        isDragging = false
        draggableRef.value?.pause()
        if (document.querySelector('.dragClass')) document.querySelector('.dragClass').style.opacity = 0;
        for (const dict of dicts.value) {
            if (dictBak[dicts.value.indexOf(dict)] !== dict) {
                commitSort()
                break
            }
        }
    }
}

onMounted(() => {
    getSetting()
})

useEventListener("keydown", (e) => {
    drag(e)
})

useEventListener("keyup", (e) => {
    dragEnd(e)
})
</script>

<style scoped>
:deep(ul) {
    padding-inline-start: 0;
    margin-block-start: 0;
    margin-block-end: 0;
}

:deep(.dict-card) {
    min-width: 220px;
    position: relative
}

:deep(.dict-card .el-card__body) {
    padding: 0;
}

:deep(.el-scrollbar__bar.is-horizontal),
:deep(.el-scrollbar__bar.is-vertical) {
    width: 0 !important;
    height: 0 !important;
}

:deep(.el-scrollbar__wrap) {
    overflow-x: hidden;
}

:deep(.saveButton) {
    border: 1px solid transparent;
    border-radius: 5px;
    background-color: #b7f4d8;
    width: 5px;
    height: 100%;
}

:deep(.newButton) {
    border: 1px solid transparent;
    border-radius: 5px;
    background-color: #e4d9f1;
    width: 5px;
    height: 100%;
}

:deep(.el-input.is-disabled .el-input__inner) {
    cursor: default;
}

:deep(.el-radio__label) {
    font-size: 12px !important;
    padding-left: 5px !important;
}

:deep(.el-card__header) {
    padding: 10px 10px;
    height: 40px;
}

:deep(.el-form-item__label) {
    text-align: left;
    padding-left: 10px;
    line-height: 15px;
    line-height: calc(var(--font-size) * 2 + 3px);
}

:deep(.el-card__body .el-form-item) {
    margin-bottom: 15px !important;
}

:deep(.el-card__body .el-form-item:last-child) {
    margin-bottom: 0 !important;
}

:deep(.el-loading-mask) {
    border-radius: 5px;
    border-bottom: none;
    border-right: none;
}

/*错误提示信息位置*/
:deep(.el-form .el-form-item__error) {
    top: 26%;
    right: 5%;
    left: unset;
    font-size: calc(var(--font-size) - 4px);
}

:deep(.el-form-item__error) {
    padding-top: 1px;
}

:deep(.el-col-12) {
    height: 10px;
}

:deep(.el-radio-button__orig-radio:disabled + .el-radio-button__inner) {
    cursor: default;
}

:deep(.el-dropdown-menu__item.is-disabled) {
    background-color: #ecf5ff !important;
    color: #66b1ff !important;
}

:deep(.el-button--large) {
    font-size: 20px;
}

:deep(.el-radio-button__inner) {
    font-weight: var(--font-weight) !important;
}

:deep(.title-page) {
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
    position: relative;
    height: 100%;
    max-width: 250px;
    background: transparent !important;
    backdrop-filter: var(--overlay-background-filter-blur) !important;
}

:deep(.content-page) {
    margin-left: 5px;
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
    position: relative;
    height: 100%;
    max-width: calc(100% - 255px);
    background-color: transparent !important;
    backdrop-filter: var(--overlay-background-filter-blur) !important;
}

:deep(.el-radio-button__original-radio:disabled+.el-radio-button__inner),
:deep(.el-dropdown-menu__item.is-disabled) {
    cursor: default;
}

:deep(.title-select) {
    background: rgba(228, 228, 228, .8) !important;
}

.dark .title-select {
    background: rgba(168, 168, 168, .6) !important;
}

:deep(.chosenClass .saveButton) {
    background: rgba(118, 118, 118, .9) !important;
}

:deep(.empty-data) {
    width: 50%;
    display: block;
    margin: 10% auto 0 auto;
    text-align: center
}

:deep(.el-scrollbar__view) {
    height: auto;
}

:deep(.title-item) {
    background: rgba(255, 255, 255, .2);
}

:deep(.title-item:hover) {
    background: rgba(255, 255, 255, .5);
}

:deep(.card-modal) {
    height: 100%;
    width: 100%;
    background: #eee;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    opacity: .2;
}
</style>